from django.shortcuts import render,redirect
#导包
from django.http import HttpResponse,HttpResponseRedirect,JsonResponse
#导入类视图
from django.views import View

from myapp.models import User
import json
from django.core.serializers import serialize
from rest_framework.response import Response
from rest_framework.views import APIView
#导入加密库
import hashlib

import hmac
import base64
from hashlib import sha256
import urllib

import datetime

#导入图片库
#绘画库
from PIL import ImageDraw
#字体库
from PIL import ImageFont
#图片库
from PIL import Image
#随机库
import random
#文件流
import io

import requests

#导入上传文件夹配置
from mydjango.settings import UPLOAD_ROOT
import os

#导入原生sql模块
from django.db import connection

import jwt

#导入redis数据库
import redis

#导入时间模块
import time

#导入公共目录变量
from mydjango.settings import BASE_DIR

#导包
from django.db.models import Q,F

#导入dwebsocket的库
from dwebsocket.decorators import accept_websocket
import uuid

#导入正则
import re

import cv2

import json

from .myser import UserSer,CarouselSer,CategorySer,GoodsSer

from myapp.models import User,Carousel,Goods,Category


import redis

#定义ip和端口
host = 'localhost'
port = 6379

#建立连接
r = redis.Redis(host=host,port=port)



#商品详情页
class GoodInfo(APIView):

    def get(self,request):

        id = request.GET.get('id',None)
        #查询
        good = Goods.objects.get(id=int(id))

        good_ser = GoodsSer(good)
        print(id)
        # 存入商品小图
        # r.lpush(good.name,'158821412404.png')
        # r.lpush(good.name,'15882149524d43f5963be83ee3eac51ea5e0ad3b4.png')
        # r.lpush(good.name,'158821412404.png')
        # r.lpush(good.name,'158864245002d5440beb417c3770afa00e005bcf3b.jpg')
        # r.lpush(good.name,'7f0fddc52e286dd655fa18dffd2e0d08_waifu2x_art_noise3_scale_tta_1.png')

        # print(r.lrange(good.name,0,5))
        
        #定义空列表添加商品小图
        l = []
        for i in r.lrange(good.name,0,5):
            l.append(i.decode('utf-8'))

        return Response({
            'data':good_ser.data,
            'l':l
        })



#格式化结果集
def dictfetch(cursor):

    #声明描述符
    desc = cursor.description

    return [ dict( zip([col[0] for col in desc],row )) 
            for row in cursor.fetchall()
    ]



#搜索接口
class Search(APIView):

    def get(self,request):

        #检索字段
        text = request.GET.get('text',None)

        #转换数据类型
        text = json.loads(text)

        sql = ''
        #动态拼接
        for val in text:
            sql += "or name like '%%%s%%' " % val
            print(sql)

        sql  = sql.lstrip('or')
        #建立游标对象
        cursor = connection.cursor()

        #执行sql
        cursor.execute("select name,id,img,price from goods where id !=0 and (" + sql + ")")

        #查询
        result = dictfetch(cursor)
        print(result)
        return Response({
            'data':result
        })


#商品列表页
class GoodsList(APIView):

    def get(self,request):

        #检索字段
        text = request.GET.get('text',None)

        #排序字段
        coloum = request.GET.get('coloum',None)

        #排序方案
        sort_order = request.GET.get('order','')

        print(coloum,sort_order)

        #当前页
        page = request.GET.get('page',1)

        #一页显示个数
        size = request.GET.get('size',1)

        #计算从哪儿开始切
        data_start = (int(page)-1)*int(size)
        #计算切到哪儿
        data_end = int(page) * int(size)


        if coloum:
            keyword = sort_order+coloum
            goods = Goods.objects.all().order_by(keyword)[data_start:data_end]
        
        else:
            goods = Goods.objects.all()[data_start:data_end]

        #判断是否进行模糊查询
        if text:
            #将text转为列表
            text = eval(text)
            goods_list = []
            for i in text:
                goods = Goods.objects.filter(Q(name__contains=i) | Q(desc__contains=i))
                for j in goods:
                    goods_list.append(j)
            
            #对商品列表进行去重
            goods_list= list(set(goods_list))
            print(goods_list)
            #获取总数量
            count = len(goods_list)
            #分页
            goods = goods_list[data_start:data_end]
        else:
            #查询所有商品个数
            count = Goods.objects.count()



        goods_ser = GoodsSer(goods,many=True)

        return Response({
            'data':goods_ser.data,
            'total':count
        })





#商品分类接口
class CategoryList(APIView):

    def get(self,request):

        category = Category.objects.all()

        category_ser = CategorySer(category,many= True)

        return Response(category_ser.data)




#商品入库接口
class InsertGoods(APIView):

    def get(self,request):

        #接参
        name = request.GET.get('name',None)

        price = request.GET.get('price',None)

        params = request.GET.get('params',None)

        cid = request.GET.get('cid',None)

        #排重操作
        goods = Goods.objects.filter(name=name).first()

        if goods:
            return Response({
                'code':403,
                'mes':'您已经添加过该商品'
            })

        #入库
        goods = Goods(name=name,price=price,params=params,cid=int(cid))

        goods.save()


        #获取已存入的商品信息
        goods = Goods.objects.filter(name=name).first()
        #存入redis  key为商品id，value为params
        r.set(goods.id,params)

        return Response({
            'code':200,
            'mes':'添加商品成功'
        })